﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPM.Entity;
using BPM.Common;
using System.Data.Entity;

namespace BPM.Service
{
	public class MaterialDefinitionCategoryService : ServiceBase<MaterialDefinitionCategory>
	{
		protected override IQueryable<MaterialDefinitionCategory> PrepareToQuery(DbSet<MaterialDefinitionCategory> set)
		{
			return base.PrepareToQuery(set)
				.Include(c => c.SubCategoryList);
		}

		protected override void EnableLazyLoadingCore(MaterialDefinitionCategory entity)
		{
			base.EnableLazyLoadingCore(entity);

			EnableChildrenLazyLoading(entity.SubCategoryList);
		}

		public override IList<MaterialDefinitionCategory> GetAll()
		{
			return this.EnableLazyLoading(
				this.Query().OrderBy(c => c.CreateTime).ToList()
				);
		}

		public IList<MaterialDefinitionCategory> GetBigCates()
		{
			return this.EnableLazyLoading(
				this.Query().Where(c => c.ParentCategoryId == null).OrderBy(c => c.CreateTime).ToList()
				);
		}

		public Result Create(string name, out MaterialDefinitionCategory entity)
		{
			entity = null;

			if (string.IsNullOrWhiteSpace(name)) return "名字不能为空。";

			entity = new MaterialDefinitionCategory()
			{
				Name = name,
				CreateTime = DateTime.Now
			};

			return this.Create(entity);
		}

		public Result CreateSubCate(int bigCateId, string name, out MaterialDefinitionCategory entity)
		{
			entity = null;

			if (string.IsNullOrWhiteSpace(name)) return "名字不能为空。";

			var bigCate = this.GetById(bigCateId);
			if (bigCate == null) return "找不到指定的对象";
			if (bigCate.ParentCategoryId != null) return "系统暂时只支持一级类别";

			entity = new MaterialDefinitionCategory()
			{
				Name = name,
				//ParentCategory = bigCate,
				ParentCategoryId = bigCateId,
				CreateTime = DateTime.Now
			};

			return this.Create(entity);
		}

		public Result ChangeName(int id, string name)
		{
			var context = this.NewContext();

			var e = context.Set<MaterialDefinitionCategory>().FirstOrDefault(c => c.Id == id);
			if (e == null) return "没有找到指定的对象。";

			e.Name = name;

			return context.Save();
		}
	}
}